<template>
  <div class="info-page">
    <!-- 顶部：返回 | 详情 -->
    <div class="page-header">
      <a-button type="link" class="back" @click="goBack">
        <LeftOutlined class="back-icon" />
        返回
      </a-button>
      <span class="sep">|</span>
      <span class="title">详情</span>
    </div>

    <!-- 新父级 -->
    <div class="content-area">
      <div v-if="loading" class="loading">正在加载...</div>
      <div v-else-if="error" class="error">{{ error }}</div>

      <!-- 正文 -->
      <div v-else class="info-body">
        <div class="row">
          <div class="label">敏感词：</div>
          <div class="value">{{ info.word || "—" }}</div>
        </div>

        <div class="row">
          <div class="label">启用状态：</div>
          <div class="value">
            <a-radio-group v-model:value="enabledShown" disabled>
              <a-radio :value="true">启用</a-radio>
              <a-radio :value="false">停用</a-radio>
            </a-radio-group>
          </div>
        </div>

        <div class="row">
          <div class="label">一级分类：</div>
          <div class="value">{{ info.cat1 || "—" }}</div>
        </div>

        <div class="row">
          <div class="label">二级分类：</div>
          <div class="value">{{ info.cat2 || "—" }}</div>
        </div>

        <div class="row">
          <div class="label">匹配方式：</div>
          <div class="value">{{ matchModeText }}</div>
        </div>

        <div class="row">
          <div class="label">处理方式：</div>
          <div class="value">{{ handleModeText }}</div>
        </div>
      </div>

      <!-- 底部 -->
      <div class="page-footer">
        <div class="footer-inner">
          <a-button
            type="link"
            class="foot-btn primary"
            :disabled="!info.id"
            @click="onEdit"
            >编辑</a-button
          >
          <span class="vsep">|</span>
          <a-button type="link" class="foot-btn ghost" @click="goBack"
            >返回</a-button
          >
        </div>
      </div>

      <div class="bottom-gap" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, onMounted, watch, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { LeftOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { getSensativeWordById } from "@/api/modules/sensativeWords.api";

const DEFAULT_TAB = "sensitive";
const route = useRoute();
const router = useRouter();

type Info = {
  id?: string | number;
  word?: string;
  enabled?: boolean;
  status?: "enabled" | "disabled";
  cat1?: string;
  cat2?: string;
  matchMode?: "contain" | "exact" | string;
  handleMode?: "过滤" | "删除" | "filter" | "block" | string;
};

const info = reactive<Info>({});
const rawItem = ref<any>(null);
const loading = ref(false);
const error = ref("");
const currentTab = computed(() => (route.query.tab as string) || DEFAULT_TAB);

function unwrapItem(res: any) {
  if (res && typeof res === "object") {
    if (res.data && res.data.data && typeof res.data.data === "object") {
      return res.data.data;
    }
    if (res.data && typeof res.data === "object" && res.data.id !== undefined) {
      return res.data;
    }
  }
  return res;
}

/** 映射为页面展示结构 */
function normalizeToInfo(item: any): Info {
  const statusRaw = String(item?.status || "").toLowerCase();
  const enabled = ["published", "active", "enabled"].includes(statusRaw);

  const cat1 =
    item?.firstcode?.first_query ??
    (typeof item?.firstcode === "string" || typeof item?.firstcode === "number"
      ? String(item.firstcode)
      : "");

  const cat2 =
    item?.secondnode?.second_query ??
    item?.secondcode?.second_query ??
    (typeof item?.secondnode === "string" ||
    typeof item?.secondnode === "number"
      ? String(item.secondnode)
      : "");

  const t = String(item?.sensative_type ?? "").toLowerCase();
  const handleMode =
    t === "filter"
      ? "过滤"
      : ["block", "delete", "remove"].includes(t)
      ? "删除"
      : item?.sensative_type ?? "—";

  return {
    id: item?.id,
    word: item?.sensative_word ?? item?.name ?? "",
    enabled,
    status: enabled ? "enabled" : "disabled",
    cat1: cat1 || "",
    cat2: cat2 || "",
    matchMode: "contain",
    handleMode,
  };
}

async function initFromRoute() {
  error.value = "";
  const rawRow = route.query.row as string | undefined;
  if (rawRow) {
    try {
      const row = JSON.parse(decodeURIComponent(rawRow));
      rawItem.value = row;
      Object.assign(info, normalizeToInfo(row));
      return;
    } catch {}
  }
  const id = (route.query.id as string | undefined) ?? undefined;
  if (!id) {
    error.value = "未提供 ID，无法加载详情";
    return;
  }
  await fetchById(id);
}

/** 通过 id 拉详情 */
async function fetchById(id: string | number) {
  loading.value = true;
  try {
    const fields = [
      "id",
      "sensative_word",
      "sensative_type",
      "status",
      "firstcode.id",
      "firstcode.first_query",
      "secondnode.id",
      "secondnode.second_query",
      "date_created",
      "user_created.id",
      "user_created.email",
    ];
    const res = await getSensativeWordById(String(id), fields as any);
    const item = unwrapItem(res);
    if (!item || typeof item !== "object") {
      error.value = "未查询到该记录";
      return;
    }
    rawItem.value = item;
    const mapped = normalizeToInfo(item);
    Object.assign(info, mapped);
    sessionStorage.setItem("sensitive_row_" + id, JSON.stringify(item));
  } catch (e: any) {
    const msg =
      e?.response?.data?.errors?.[0]?.message || e?.message || "获取详情失败";
    error.value = msg;
    message.error(msg);
  } finally {
    loading.value = false;
  }
}

onMounted(initFromRoute);
watch(() => route.fullPath, initFromRoute);

/** 启用单选显示值 */
const enabledShown = computed<boolean>(() => {
  if (typeof info.enabled === "boolean") return info.enabled;
  if (info.status) return info.status === "enabled";
  return true;
});

/** 匹配方式 */
const matchModeText = computed(() => {
  const m = (info.matchMode || "").toString().toLowerCase();
  if (m === "contain" || m === "包含匹配") return "包含匹配";
  if (m === "exact" || m === "完全匹配") return "完全匹配";
  return "—";
});

/** 处理方式 */
const handleModeText = computed(() => {
  const h = (info.handleMode || "").toString().toLowerCase();
  if (h === "过滤" || h === "filter") return "过滤";
  if (h === "删除" || ["block", "delete", "remove"].includes(h)) return "删除";
  return info.handleMode || "—";
});

/** 返回、编辑 */
function goBack() {
  router.push({ path: "/", query: { tab: currentTab.value } });
}

function onEdit() {
  if (!info.id) return;
  const rowPayload = rawItem.value
    ? rawItem.value
    : {
        id: info.id,
        sensative_word: info.word,
        status: info.status === "enabled" ? "published" : "draft",
      };

  router.push({
    path: "/sensitiveLexiconPage",
    query: {
      tab: currentTab.value,
      mode: "edit",
      backTo: "tab",
      id: String(info.id),
      row: encodeURIComponent(JSON.stringify(rowPayload)),
    },
    state: { row: rowPayload },
  });
}
</script>

<style lang="less" scoped>
@pad-x: 24px;
@wrap-max: 720px;
@label-w: 88px;
@safe-bottom: env(safe-area-inset-bottom);

.info-page {
  --footer-h: 56px;

  display: flex;
  flex-direction: column;
  min-height: 100vh;
  min-height: 100dvh;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
  background: #fff;

  font-family: "PingFang SC", -apple-system, BlinkMacSystemFont, "Segoe UI",
    Roboto, "Helvetica Neue", Arial, sans-serif;

  .page-header {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 24px @pad-x;
    border-bottom: 1px solid #f0f0f0;

    .back.ant-btn {
      display: inline-flex;
      align-items: center;
      padding-left: 24px;
      height: 24px;
      line-height: 24px;
      font-size: 14px;
      color: #81889c;

      .back-icon {
        font-size: 16px;
      }
    }

    .sep {
      color: #d9d9d9;
    }

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #000;
    }
  }

  /* 新父级 */
  .content-area {
    flex: 1 1 auto;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    overflow-x: hidden;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: contain;
    padding-bottom: calc(16px + @safe-bottom);

    /* 自定义滚动条 */
    &::-webkit-scrollbar {
      width: 10px;
      height: 10px;
    }
    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.15);
      border-radius: 6px;
      border: 2px solid transparent;
      background-clip: padding-box;
    }
    &::-webkit-scrollbar-thumb:hover {
      background: rgba(0, 0, 0, 0.25);
    }
    &::-webkit-scrollbar-track {
      background: transparent;
    }
    scrollbar-width: thin;
    scrollbar-color: rgba(0, 0, 0, 0.25) transparent;
    scrollbar-gutter: stable;
  }

  .loading,
  .error,
  .info-body {
    padding: 24px @pad-x 0 140px;
    box-sizing: border-box;
  }

  .loading {
    color: #666;
  }
  .error {
    color: #ff4d4f;
  }

  .info-body {
    .row {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      min-height: 24px;
      margin: 0 0 24px 0;
      width: 100%;
      max-width: (@wrap-max + @label-w);
    }

    .label {
      width: @label-w;
      line-height: 24px;
      color: #333;
      font-size: 14px;
      flex: 0 0 auto;
    }

    .value {
      flex: 1 1 auto;
      font-size: 14px;
      line-height: 24px;
      word-break: break-word;
    }
  }

  /* 底部操作 */
  .page-footer {
    position: static;
    margin-top: 16px;
    padding: 12px @pad-x calc(12px + @safe-bottom) @pad-x;
    background: #fff;
    border-top: 1px solid #f0f0f0;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.03);

    .footer-inner {
      width: 100%;
      max-width: (@wrap-max + @label-w);
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 12px;
      flex-wrap: wrap;
      text-align: center;
    }

    .vsep {
      color: #e5e7eb;
      user-select: none;
      line-height: 24px;
      height: 24px;
      display: inline-flex;
      align-items: center;
      margin: 0 2px;
    }

    .foot-btn {
      height: 36px;
      // min-width: 108px;
      padding: 0 20px;
      border-radius: 8px;
      font-weight: 600;
      transition: box-shadow 0.2s ease, filter 0.2s ease, background 0.2s ease,
        border-color 0.2s ease;

      &.primary {
        background: #1677ff !important;
        border: 1px solid #1677ff !important;
        color: #fff !important;
        &:hover {
          filter: brightness(1.02);
          box-shadow: 0 2px 8px rgba(22, 119, 255, 0.2);
        }
      }

      &.ghost {
        background: #fafafa !important;
        border: 1px solid #e8e8e8 !important;
        color: #666 !important;
        &:hover {
          background: #fff !important;
          color: #595959 !important;
          border-color: #d9d9d9 !important;
        }
      }
    }
  }

  .bottom-gap {
    height: 8px;
  }

  /* 小屏优化 */
  @media (max-width: 576px) {
    .page-header {
      padding: 16px 12px;
    }
    .loading,
    .error,
    .info-body {
      padding: 16px 12px 0 12px;
    }
    .page-footer {
      padding-left: 12px;
      padding-right: 12px;
    }
    .page-footer .footer-inner {
      max-width: none;
    }
  }
}

.top-divider,
.bottom-divider {
  display: none;
}
</style>
